<?php

namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Shop\Core\Models\Clerk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use RuntimeException;

class AuthController extends Controller
{

    private $clerk;

    public function __construct(Clerk $clerk)
    {
        $this->clerk = $clerk;

    }

    protected function guard()
    {
        return auth()->guard('clerk');
    }

    public function test()
    {
        return 'aa';
    }

    public function issueToken(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        if (is_null($model = config('auth.providers.clerk.model'))) {
            throw new RuntimeException('Unable to determine clerk model from configuration.');
        }

        if (!$user = $model::where(['mobile' => $username])->first()) {
            return $this->response()->errorUnauthorized('用户不存在');
        }

        if (empty($user->password) || !Hash::check($password, $user->password)) {
            return $this->response()->errorUnauthorized('密码验证失败');
        }

        if ($user->status == 0) {
            return $this->api([], false, 403, '您的账号已被禁用，联系管理员！');
        }

        $token = $user->createToken($user->mobile)->accessToken;

        return $this->api(['token_type' => 'Bearer', 'access_token' => $token, 'clerk' => $user], true, 200, '登陆成功');

    }

}